<template>
	<view class="content">
		<view  class="head_nav" :style="{background: 'url('+ bgurl +'/policy/user_img/my_bg.png)'}">
			<view class="navs" >
				<!-- <image style="width: 100%;position: absolute; z-index: -1;" src="@/static/picture/indexbg.png" mode="widthFix" lazy-load></image> -->
				<!-- #ifdef MP-WEIXIN -->
				<view class="wid" :style="{height: `${statusBarHeight}px`}"></view>
				<!-- #endif --> 
				<!-- #ifdef MP-WEIXIN -->
				<view class="navbar"  :style="{height: `${titleBarHeight}px`}">
					<!-- #ifdef MP-WEIXIN -->
					<view :style="{lineHeight: `${titleBarHeight}px` }">订单</view>
					<!-- #endif --> 
				</view> 
				<!-- #endif --> 
			</view>  
			<view class="tabsnav">
				<!-- #ifdef MP-WEIXIN -->
				<uv-tabs  :list="tab1" lineWidth="30" lineHeight='4' lineColor="#AD8539" :scrollable= 'false'  :current='tabindex'
					:activeStyle="{ color: '#303133',fontWeight: 'bold',transform: 'scale(1.05)'}"
					:inactiveStyle="{color: '#828282',transform: 'scale(1)'}" 
					itemStyle="height: 92rpx;font-size:30rpx"
					@click="tabshow" 
					></uv-tabs> 
				<!-- #endif --> 
				<!-- #ifdef H5 -->
				<uv-tabs  :list="tab1" lineWidth="30" lineHeight='4' lineColor="#FFBF00" :scrollable= 'false'  :current='tabindex'
					:activeStyle="{ color: '#fff',fontWeight: 'bold',transform: 'scale(1.05)'}"
					:inactiveStyle="{color: '#fff',transform: 'scale(1)'}" 
					itemStyle="height: 92rpx;font-size:30rpx"
					@click="tabshow"
					></uv-tabs> 
				<!-- #endif --> 
				 </view>  
		 </view>  
		 <!-- #ifdef MP-WEIXIN --> 
		  <view :style="{height:'calc(105rpx + '+ allBarHeight+'px)'}"></view>
		 <!-- #endif --> 
		 <!-- #ifdef H5 --> 
		 	 <view :style="{height: `${allBarHeight}px`}"></view>
		 <!-- #endif --> 
		 
		 <view v-if="orderlists.length!=0" class="order_list" >  
			 <view class="order_item" v-for="(item,index) in orderlists" :key="item.id" @click="orderinfo(item.id)">
				<view class="order_t fx-row-s"  >
					<view class="order_img">
						<image :src="item.serviceCover" mode="heightFix" lazy-load></image>
					</view>
					<view class="order_info fx-col-sb">
						<view class="fx-row-sb">
							<span class="ft32 " style="font-weight: bold;">{{item.serviceName}}</span>
							<span class="ft28" v-if="item.status.code== '10'" style="color:#F82323"><!--待付款-->{{item.status.desc}}</span>
							<span class="ft28" v-if="item.status.code== '20'" style="color:#F82323;"><!--待接单-->{{item.status.desc}}</span>
							<span class="ft28" v-if="item.status.code== '99'" style="color:#B80048;"><!--已取消-->{{item.status.desc}}</span>
							<span class="ft28" v-if="item.status.code== '30'" style="color:#FF7700;"><!--进行中-->{{item.status.desc}}</span>
							<span class="ft28" v-if="item.status.code== '40'" style="color:#41C088;"><!--已完成-->{{item.status.desc}}</span>  
						</view>
						<view class="mt10 ft24 grey4">技师：{{item.massagistName}}</view>
						<!-- <view class="mt2 ft24 grey4">出行费用：{{conversion(item.travelPrice)}}</view> -->
						<view class="ft24 grey4">订单费用：{{conversion(item.orderPrice)}}</view>
						<!-- <view class="mt2 ft24 grey4">订单时间：{{item.createTime}}</view> -->
						<view class="ft24 grey4">预约时间：{{item.appointTime}}</view>
						<view  v-if="item.status.code== '99'" class="ft24 grey4 text-beyond "  style="width: 400rpx;">取消原因：{{item.cancelReason}}</view>
					</view>
				</view>  
				<view class="order_btns fx-row-end-c" v-if="item.status.code== '10' || item.status.code== '20' || item.status.code=='30' || item.status.code=='99'">
					<block v-if="item.operateStatus!=null">
						<span v-if="item.status.code== '10' || item.status.code== '20' || (item.status.code=='30'&&(item.operateStatus.code=='31'||item.operateStatus.code=='32'||item.operateStatus.code=='33'))" class="btn obtn1" @click.stop="escOrders(item.id)">取消订单</span>
					</block> 
					<span v-if="item.status.code== '10'" class="btn obtn2" @click.stop="goPay(item.id)">去支付</span> 
					<block v-if="item.operateStatus!=null">
						<span v-if="item.status.code== '30'&&(item.operateStatus.code=='34'||item.operateStatus.code=='35')" class="btn obtn2" @click.stop="addTime(item)">立即加钟</span>
					</block>
					<span v-if="item.status.code== '99'" class="btn obtn2" @click.stop="againOrder(item)">再来一单</span>
				</view>
				<view class="order_btns fx-row-end-c" v-if="item.status.code== '40' && !item.hasComments"  > 
					<span  class="btn obtn3" @click.stop="appraise(item,index)">立即评价</span>  
				</view>
			 </view> 
			  <uv-load-more :status="isLoading" fontSize='12' color='#696969' nomoreText=' '/>
		 </view>
		 <!-- 缺省状态 --> 
		 <empty v-else title='您还没有相关订单'></empty>
		 <!-- 取消订单 -->
		<uv-popup class="esc_popup" ref="escpop" mode='bottom'  zIndex='9999' round="12" duration='300' closeable @change="cpopup">
			<view class="esccon">
				<view class="ft32 ta">取消订单</view>
				<uv-radio-group class="escgroup mt16" v-model="radiovalue" @change="cradio" placement="column" iconPlacement="right" activeColor="#AD8539" labelSize="14">
					<uv-radio 
						:customStyle="{height: '80rpx'}" 
						v-for="(item, index) in radiolist" 
						:key="index" 
						:label="item.name" 
						:name="item.name">
					</uv-radio>
				</uv-radio-group> 
				<view class="escbtn" @click="sureEsc">确认取消</view>  
			</view>
		</uv-popup>
		<!-- 立即加钟 -->
		<uv-popup mode='bottom'  zIndex='991' round="12" duration='300' closeable ref="popup" >
				<!-- <subscribe ref="cou" :state="stateindex" :projectList="projectLists" allPrices='0.00' :projectInfo="projectInfo" @addProject='addProject'  @goInfor='goInfor'></subscribe> -->
				<subscribeList ref="cou" :state="stateindex" :projectList="projectLists" :projectInfo="projectInfo"   @addProject='addProject' @goInfor='goInfor'></subscribeList> 
		</uv-popup>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	import { orderList,extraTime,orderPay,massagistDetails,escOrder,geturl,extOrderPay } from '@/utils/api.js'
	import badgeMix from '@/common/mixins.js'
	import subscribe from '@/components/subscribe.vue'
	import subscribeList from '@/components/subscribe-list.vue' 
	import empty from '@/components/empty.vue'
	import config from '@/config.js' 
	export default {
		mixins: [badgeMix], 
		components:{subscribe,subscribeList,empty},
		data() {
			return {
				titleBarHeight:this.titleBarHeight,
				statusBarHeight:this.statusBarHeight,
				allBarHeight:this.allBarHeight, 
				tab1: [{
					name: '全部',
					state:''
				}, {
					name: '待付款', 
					 state:'10'
				}, {
					name: '进行中',
					state:'30'
				}, {
					name: '已完成',
					state:'40'
				}, {
					name: '已取消',
					state:'99'
				}],
				tabindex:'0',
				liststate:'',
				orderlists:[],
				radiolist: [
					{
						name: '行程有变',
						disabled: false
					}, {
						name: '时间太晚',
						disabled: false
					},{
						name: '车费太贵',
						disabled: false
					}, {
						name: '超出接单范围',
						disabled: false
					}, {
						name: '等待时间太长',
						disabled: false
					}, {
						name: '支付出现异常',
						disabled: false
					}, {
						name: '其他原因',
						disabled: false
					} ,
				],
				radiovalue: '', 
				isLoading:'nomore',  //是否加载中
				pageNum:1,//请求的页码
				pageSize:10,//请求的条数 
				total:1,
				timeData:{
					'orderId':'',
					'serviceId':'',
					'massagistId':'',
					'orderCount':'',
					// #ifdef MP-WEIXIN
					"source" : 'WeChatMini',
					"version" : config.appInfo.version
					// #endif
				},
				source:'',//来源
				projectLists:[],
				projectInfo:{},
				stateindex:'1',
				escOrderId:'',
				bgurl:config.imageUrl, 
			}
		},
		onShow() { 
			this.pageNum = 1
			this.orderlists = []
			this.getOrder(this.liststate)  
		}, 
		async onLoad() {  
			// await this.menuButton() 
			// #ifdef H5
			await this.$u.init()
			await this.$u.share()
			// #endif 
			// if(!uni.getStorageSync('OPENID') || uni.getStorageSync('OPENID').type == 'undefined'){
			// 	await this.$u.wxOauth()   
			// }  
		},
		methods: {  
			// 订单列表
			getOrder(state){
				this.isLoading = 'loading'
				uni.showLoading({
					title:'加载中'
				})
				const  datas = {
					"current": this.pageNum,  //页码
					"size": this.pageSize,   //条数
					"status": state ,//订单状态 10 未支付  20待接单  30进行中 40已完成  99已取消
				} 
				orderList(datas).then((res) => { 
					uni.hideLoading()
					if(res.code == '200'){
						const data = res.result.records  
						this.orderlists = [...this.orderlists,...data] 
						if(data.length < this.pageSize){ 
							this.isLoading = 'nomore'
						}
					}
				}) 
			},
			// 订单详情
			orderinfo(id){
				uni.navigateTo({
					url:'/pages/order/orderDetails?state=info&id=' + id
				})
			},
			// 再来一单
			againOrder(item){
				uni.reLaunch({
					url:'/pages/index/index'
				})
				// 项目id  技师id  项目数量  订单支付再来一单
				// uni.navigateTo({
				// 	url:`/pages/order/orderPay?pid=${item.serviceId}&mid=${item.massagistId}&num=1`
				// }) 
			},
			// 立即加钟弹窗
			addTime(item,index){
				// 技师详情
				this.timeData.orderId = item.id
				this.timeData.massagistId = item.massagistId    
				massagistDetails(this.timeData).then(async(res) => {
					console.log(res);  
					if(res.code == '200'){ 
						res.result.serviceList.forEach((item,index)=>{
							res.result.serviceList[index].num = 0
						})
						this.projectLists = res.result.serviceList
						this.projectInfo = res.result
					}
				}) 
				this.$refs.popup.open('bottom');
			},
			// 立即评价
			appraise(item){
				uni.navigateTo({
					url:"/pages/evaluate/evaluate?id="+item.id+"&massagistId="+item.massagistId+"&massagistName="+item.massagistName+"&endTime="+item.endTime+"&massagistWorkPhoto="+encodeURIComponent(JSON.stringify(item.massagistWorkPhoto))
				})
			},
			// 项目详情
			goInfor(projectId){ 
				this.$refs.popup.close();
				// // #ifdef MP-WEIXIN
				// var id = projectId.detail.__args__[0]
				// // #endif
				// // #ifdef H5
				// var id = projectId
				// // #endif
				uni.navigateTo({
					url:'/pages/index/details?id='+projectId
				})
			},
			// 加钟订单 
			addProject(addOrderId,num,mid){   
				this.timeData.serviceId = addOrderId
				this.timeData.orderCount = num 
				this.timeData.massagistId = mid
				extraTime(this.timeData).then((res) => {
					console.log(res);  
					if(res.code == '200'){
						// 加钟后直接支付
						this.extPay(res.result.id,res.result.orderId)  
					}else{
						uni.showToast({
							title:res.message,
							icon:'none'
						})
						if(res.message=='该订单状态不可加钟'){
							setTimeout(()=>{
								this.orderlists = []
								this.pageNum = 1
								this.getOrder(this.liststate)
							},1000)
						} 
					}
				}) 
				this.$refs.popup.close(); 
				// 加钟后支付
			},
			// 加钟支付
			extPay(extOrderId,orderId){ 
				// #ifdef MP-WEIXIN
				this.source = 'WeChatMini'
				// #endif 
				// #ifdef H5 
				this.source = 'WeChat'
				// #endif
				extOrderPay({"extOrderId":extOrderId,"openId":uni.getStorageSync('OPENID'),"source":this.source}).then((paydata)=>{ 
					// #ifdef MP-WEIXIN
					this.mpPay(paydata.result,orderId,'ext')   
					// #endif
					
					// #ifdef H5 
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
							"appId": paydata.result.appId,     //公众号ID，由商户传入     
							"timeStamp": paydata.result.timeStamp,     //时间戳，自1970年以来的秒数     
							"nonceStr": paydata.result.nonceStr,        //随机串     
							"package": paydata.result.packAge, 
							"signType": paydata.result.signType,    //微信签名方式：     
							"paySign":  paydata.result.paySign,  //微信签名 
					},
					function(res){
						if (res.err_msg == 'get_brand_wcpay_request:ok') {
							uni.showToast({
								title:'您已加钟，请享受服务！'
							})
							// 调用详情刷新数据
							setTimeout(()=>{
								uni.navigateTo({
									url:'/pages/order/orderDetails?state=info&id=' + orderId
								})
								// this.orderInfo(orderId) 
							},1000)  
						}
						if (res.err_msg == 'get_brand_wcpay_request:cancel') {
							uni.showToast({
								title:'支付失败！',
								icon:'none'
							})
						}
						
					} ,)
					// this.$u.init(()=>{
					// 	this.$u.wxpay({
					// 		timeStamp: paydata.result.timestamp,
					// 		nonceStr: paydata.result.nonceStr,  
					// 		package: paydata.result.packAge,  
					// 		signType: paydata.result.signType,
					// 		paySign: paydata.result.paySign,  
					// 		success:()=>{
					// 			uni.showToast({
					// 				title:'支付成功！'
					// 			})
					// 			// 调用详情刷新数据
					// 			setTimeout(()=>{
					// 				this.orderInfo(orderId) 
					// 			},1000) 
					// 		},
					// 		fail:()=>{
					// 			uni.showToast({
					// 				title:'支付失败！',
					// 				icon:'none'
					// 			})
					// 		}
					// 	})
					// })  
					// #endif
				})
			},
			// 支付
			async goPay(orderId){
				// #ifdef MP-WEIXIN
				await this.subScribeMsg().then(result => {
					console.log(result,'订阅');
					// 处理操作成功的情况，result为操作成功的结果
				}).catch(error => {
					// 处理操作失败的情况，error为发生的错误
				});
				// #endif 
				// #ifdef MP-WEIXIN
				this.source = 'WeChatMini'
				// #endif 
				// #ifdef H5 
				this.source = 'WeChat'
				// #endif
				orderPay({"orderId":orderId,"openId":uni.getStorageSync('OPENID'),"source":this.source}).then((paydata)=>{ 
					// #ifdef MP-WEIXIN
					this.mpPay(paydata.result,orderId)  
					// #endif
					
					// #ifdef H5 
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
							"appId": paydata.result.appId,     //公众号ID，由商户传入     
							"timeStamp": paydata.result.timeStamp,     //时间戳，自1970年以来的秒数     
							"nonceStr": paydata.result.nonceStr,        //随机串     
							"package": paydata.result.packAge, 
							"signType": paydata.result.signType,    //微信签名方式：     
							"paySign":  paydata.result.paySign,  //微信签名 
					},
					function(res){
						if (res.err_msg == 'get_brand_wcpay_request:cancel') {
							uni.showToast({
								title:'支付失败！',
								icon:'none'
							}) 
						}
						if (res.err_msg == 'get_brand_wcpay_request:ok') {
							uni.showToast({
								title:'支付成功！'
							}) 
							setTimeout(()=>{
								// uni.navigateTo({
								// 	url:'/pages/order/orderDetails?state=info&id=' + orderId
								// })
								uni.navigateTo({
									url:'/pages/order/paySuccess?state=info&id=' + orderId
								})
							},1000)  
						}
					})   
					// #endif
				})
			},
			//小程序支付
			mpPay(paydata,orderId,source){
				uni.requestPayment({
					provider:'wxpay',  
					timeStamp:paydata.timeStamp,
					nonceStr:paydata.nonceStr,
					package: paydata.packAge,
					signType:paydata.signType,
					paySign:paydata.paySign,
					success: function (res) {
						if(source == 'ext'){
							uni.showToast({
								title:'您已加钟，请享受服务！'
							})
						}else{
							uni.showToast({
								title:'支付成功！'
							})
						} 
						setTimeout(()=>{
							uni.navigateTo({
								url:'/pages/order/orderDetails?state=info&id=' + orderId
							})
						},1000) 
						console.log('success:' + JSON.stringify(res));
					},
					fail: function (err) {
						uni.showToast({
							title:'支付失败！',
							icon:'none'
						})
						console.log('fail:' + JSON.stringify(err));
					}
				})
			},
			tabshow(e){
				console.log(e);
				this.orderlists = []
				this.pageNum = 1
				this.liststate = e.state 
				this.getOrder(e.state)
			},
			// 取消订单
			escOrders(orderid){ 
				this.escOrderId = orderid
				this.$refs.escpop.open(); 
			},
			cpopup(e){ 
				// #ifdef MP-WEIXIN
				if(e.show){
					uni.hideTabBar()
				}else{
					setTimeout(()=>{
						uni.showTabBar()
					},300)
				}
				// #endif
			},
			cradio(e){
				console.log(e)
				this.radiovalue = e
			},
			// 确定取消订单
			sureEsc(){
				// #ifdef MP-WEIXIN
				this.source = 'WeChatMini'
				// #endif 
				// #ifdef H5 
				this.source = 'WeChat'
				// #endif
				if(!this.radiovalue){
					return uni.showToast({
						title:'请选择取消原因！',icon:'none'
					})
				} 
				this.$refs.escpop.close();
				escOrder({'id':this.escOrderId,'cancelReason':this.radiovalue,"source":this.source}).then((res) => {
					console.log(res);  
					this.radiovalue=""
					if(res.code == '200'){
						uni.showToast({
							title:'订单已取消！',
							icon:'none'
						})
						setTimeout(()=>{
							this.orderlists = []
							this.pageNum = 1
							this.getOrder(this.liststate)
						},1000)
					}else{
						uni.showToast({
							title:res.message,
							icon:'none'
						})
						if(res.message=='取消失败，技师已经开始服务了哦'){ 
							setTimeout(()=>{
								this.orderlists = []
								this.pageNum = 1
								this.getOrder(this.liststate)
							},1000)
						} 
					}
				})  
			}, 
		}, 
		// 上拉刷新
　　onReachBottom() {  
			//如果最后一次请求，数据为空的话就停止请求，防止多次触发接口
			if(this.isLoading=='nomore'){
				return;
			}
			this.pageNum++
			//调用请求接口
			this.getOrder(this.liststate)
		},
		onPullDownRefresh() {
			this.orderlists = []
			this.pageNum = 1
			this.getOrder(this.liststate)
			setTimeout(function () { 
				uni.stopPullDownRefresh();
			}, 1000);
		},
	}
</script> 
<style lang="scss">
	page{
		background-color:$uni-main-page ;
	}
	.head_nav{
		position: fixed;
		top: 0;
		width: 750rpx;	  
		// #ifdef MP-WEIXIN
		padding-bottom:30rpx ;
		// #endif 
		background-size: 100% auto !important;
		box-sizing: border-box; 
		overflow: hidden;
		z-index: 999; 
		.navs{
			// #ifdef MP-WEIXIN
			padding-bottom:30rpx ;
			// #endif 
		}
		.navbar{
			position: relative;
			text-align: center;
			font-size: 32rpx;
			color: #fff; 
		} 
		.tabsnav{
			// position: fixed; 
			width: 750rpx;	  
			// #ifdef MP-WEIXIN
			background-color: #fff;
			margin-top: -15rpx;
			// #endif 
			// #ifdef H5
			height: 90rpx;
			padding-top: 10rpx;
			margin-top: -5rpx;
			// #endif 
			
			border-radius: 12rpx 12rpx 0rpx 0rpx;
		} 
	}
	.uv-tabs{
		position: fixed;
		margin-top: -5rpx;
		width: 750rpx;	 
		height: 90rpx;
		// #ifdef MP-WEIXIN
		background-color: #fff;
		// #endif  
		border-radius: 12rpx 12rpx 0rpx 0rpx;
	} 
	.order_list{ 
		padding: 18rpx 0;
		margin-top: 0;
		.order_item{
			width: 650rpx;
			margin: 0 30rpx 16rpx 30rpx;
			padding: 0 20rpx;
			background-color: #fff;
			border-radius: 16rpx;
			.order_t{
				width: 650rpx;
				padding:20rpx 0 20rpx 0; 
				.order_img{
					width: 188rpx;
					height: 188rpx; 
					margin-right: 20rpx;
					border-radius: 10rpx;
					overflow: hidden;
					image{
						height: 100%;
					}
				}
				.order_info{
					width: 442rpx;
					height: 188rpx;
				}
			}
			.order_btns{
				border-top: 1rpx solid $uni-color-line;
				padding: 16rpx 0 20rpx 0;
				.btn{
					margin-left: 20rpx;
					padding:6rpx 26rpx ;
					border-radius: 38rpx;
					font-size: 28rpx;
				}
				.obtn1{ 
					border: 1rpx solid #D1D1D1; 
					color: #333;
				}
				.obtn2{ 
					border: 1rpx solid $uni-main;
					color: $uni-main; 
				}
				.obtn3{
					border: 1rpx solid $uni-main-warning;
					color: $uni-main-warning;
				}
			}
		}
	}
	.esc_popup{
		
		
	}
	.esccon{
		width: 670rpx;
		padding: 45rpx 40rpx;
		.escgroup{
			// height: 700rpx;
			// overflow-y: auto; 
		}
		.escbtn{
			width: 670rpx;
			height: 88rpx;
			margin-top: 40rpx;
			background-color: $uni-main;
			font-size: 36rpx;
			color: #fff;
			text-align: center;
			line-height: 88rpx;
			border-radius: 50rpx;
		}
	}
</style>
